package name.gillier.jminify;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class ApiEndPointServlet extends HttpServlet {
	
	/**
	 * Logger definition.
	 */
	private static final Logger log = Logger.getLogger(ApiEndPointServlet.class.getName());

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		resp.setContentType("text/plain");
		
		// URL
		if(req.getParameter("url").equals(null))
			throw new ServletException("No URL provided");
		
		try {
			String id = Shortener.shorten(req.getParameter("url"));
			String finalUri = this.getServletContext().getInitParameter("appUrl")+"/-/"+id;
			
			if(req.getParameter("format").equalsIgnoreCase("json"))
				resp.getWriter().println("{ \"shortUrl\": \""+finalUri+"\" } ");
			else
				resp.getWriter().println(finalUri);
			
		} catch (Exception e) {
			log.severe("Erreur API:"+e.getLocalizedMessage());
		}
	}
}
